﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WarOfDev.EF;
using WarOfDev.Core;
using WarOfDev.Core.Common;
using WarOfDev.Web.Models;
using AsyncUploaderDemo.Models;
using System.Collections;

namespace WarOfDev.Web.Controllers
{
    public class MessageController : BaseController
    {
        private WarDevEntities db = new EF.WarDevEntities();
        private IFileStore AddAttachFileGuid = new DiskFileStore();

        public Guid GetAttachFileGuid()
        {
            Guid AttachFileGuid = AddAttachFileGuid.SaveUploadedFile(Request.Files[0]);
            return AttachFileGuid;
        }


        //
        // GET: /Message/
        [ActionName("Post")]
        public ActionResult PostMessage(string message, string FileNameList, string FileGuidList)
        {
            string[] FileGuids = FileGuidList.Split(',');
            string[] FileNames = FileNameList.Split(',');
            System.Data.Objects.DataClasses.EntityCollection<WarOfDev.EF.MessageFile> MessageFileList = new System.Data.Objects.DataClasses.EntityCollection<MessageFile>();
            for (int i = 1; i < FileGuids.Length; i++ )
            {
                MessageFile obj = new MessageFile()
                {
                    Id = FileGuids[i],
                    FileName = FileNames[i],
                    CreatedBy = this.CurrentUser.Id,
                    CreatedOn = DateTime.Now
                };
                MessageFileList.Add(obj);
            }

            var m = new Message()
            {
                Id = Guid.NewGuid().ToString(),
                CreatedBy = this.CurrentUser.Id,
                CreatedOn = DateTime.Now,
                MessageContent = message,
                Files = MessageFileList
            };

            db.Messages.AddObject(m);
            db.SaveChanges();

            var returnData = new JsonResult()
                {
                    Data = new
                    {
                        success = true,
                        content = message,
                        developer = this.CurrentUser.Id,
                        currentDeveloperName = this.CurrentUser.TrueName,
                        createdOn = DateTime.Now,
                        messageLinks = m.Links,
                        messageID = m.Id,
                        MessageFiles = m.Files
                    }
                };

            return returnData;
        }

        public ActionResult Reply(string id, string message)
        {

            Message msg = new Message()
            {
                Id=Guid.NewGuid().ToString(),
                ReferTo=id,
                CreatedBy=this.CurrentUser.Id,
                CreatedOn=DateTime.Now,
                MessageContent=message
            };

            db.Messages.AddObject(msg);
            db.SaveChanges();

            return new JsonResult { 
                Data= new{ success=true,
                           developer=this.CurrentUser.NickName
                             }
            };


        }

        public ActionResult Like(string id)
        {

            var operation = new MessageOperation
            {
                CreatedBy = this.CurrentUser.Id,
                CreatedOn = DateTime.Now,
                Id = Guid.NewGuid().ToString(),
                MessageId = id,
                OperateType = (int)EnumMessageOprateType.Like
            };

            
            db.MessageOperations.AddObject(operation);
            db.SaveChanges();

            return new JsonResult
            {
                Data = new { success = true }
            };
        }

        public ActionResult UnLike(string id)
        {

            var operation = db.MessageOperations.Single(o => o.OperateType == (int)EnumMessageOprateType.Like &&
                                                        o.MessageId == id
                                                        && o.CreatedBy == this.CurrentUser.Id);

            db.MessageOperations.DeleteObject(operation);
            db.SaveChanges();

            return new JsonResult
            {
                Data = new { success = true }
            };
        }


        public ActionResult List()
        {

            var messages = db.Messages.Include("Developer").Include("Links").Include("Operations").Include("Files")
                                      .OrderByDescending(m => m.CreatedOn)
                                      .Where(s=> string.IsNullOrEmpty(s.ReferTo))
                                      .ToList();

            var ids = messages.Select(m => m.Id).ToList();

            var refMessages = db.Messages.Include("Developer").Include("Links").Include("Operations")
                                      .OrderByDescending(m => m.CreatedOn)
                                      .Where(s => !string.IsNullOrEmpty(s.ReferTo))
                                      .Where(s=> ids.Contains(s.ReferTo))
                                      .ToList();

            var list = new List<Models.MessageModel>();
            messages.ForEach(m => { 
                var model=new Models.MessageModel(m);
                model.ReplyList.AddRange(refMessages.Where(r => r.ReferTo == m.Id));
                list.Add(model);
            });


            return PartialView(list);
        }

        //Downlaod: get file from disk
        public FilePathResult GetFileFromDisk(string Id)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "App_Data\\Files/";
            string fileName = path+Id;
            return File(fileName+".png", "text/plain", "test");
        }


    }
}
